package org.icec.iot.mqtt.server.auth.service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AclService {
	@Value(value = "classpath:config/aclfile.json")
	private Resource aclFile;
	private Map<String,String[]> aclMap=new HashMap<String,String[]>();
	/**
	 * 检查用户topic权限
	 * 
	 * @param mode
	 * @param role
	 * @param topic
	 * @return
	 */
	public boolean checkTopic(String mode, String role, String topic,String clientId) {
		String[] topics=aclMap.get(role+"_"+mode);
		for(String acl:topics) {
			acl=acl.replace("${clientId}", clientId);
			if(acl.equals("*")) {
				return true;
			}else if(topic.startsWith(acl)){
				return true;
			}
		}
		log.debug("{}无权限topic:{}",role,topic);
		return false;
	}

	@PostConstruct
	private void init() {
		try {
			InputStream inputStream = new FileInputStream(aclFile.getFile());
			ObjectMapper mapper = new ObjectMapper(); 
			JsonNode rootNode =mapper.readTree(inputStream);
			Iterator<Entry<String, JsonNode>> it=rootNode.fields();
			while(it.hasNext()) {
				 Entry<String, JsonNode> entry = it.next();
				 String role=entry.getKey();
				String read= entry.getValue().path("read").asText();
				String[]  readstrs=read.split(",");
				aclMap.put(role+"_read", readstrs);
				String write= entry.getValue().path("write").asText();
				String[]  writestrs=write.split(",");
				aclMap.put(role+"_write", writestrs);
			}
		} catch (IOException e) {
			log.info("读取acl file 异常", e);
		}
	}
}
